package com.ylw.project;


import java.io.*;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

/**
 * 为了生成文件目录
 * 目前可以替换 src下面生成的class文件和domain*.xml文件
 *
 * 内部类暂时无法处理 classname$innername[1,2]
 *
 *  切换到D:\ideaproject1\IW\target\classes 可以直接运行该脚本
 * java -Dfile.encoding=UTF-8 -classpath "D:\ideaproject1\IW\target\classes;C:\Users\ShawnLuo\.m2\repository\log4j\log4j\1.2.17\log4j-1.2.17.jar;C:\Users\ShawnLuo\.m2\repository\commons-logging\commons-logging\1.1.1\commons-logging-1.1.1.jar;" com.ylw.project.Project
 *
 *  新的流程 使用nio 和threadpoolexecutor
 *
 */
public class Project {

    private static final Logger logger = Logger.getLogger(Project.class);
//    public static final String OUTPUT_ROOTDIR = "C:\\Users\\ShawnLuo\\Desktop\\test";
    public static final String OUTPUT_ROOTDIR = "C:\\Users\\ShawnLuo\\Desktop\\test";
    public static final String SUFFIX = ".war";
    public static final String[] SRC_INCLUDE = {".class", ".xml", ".properties",".ftl"};
    public static final String[] HTML_INCLUDE = {"js", "css", "whtml","html","png"};
    public static final String[] WEB_INF_INCLUDE = {"web.xml"};
    private String projectName;


    /**
     * 将class文件夹下面的class和xml以及properties文件路径换成项目里面的相对路径
     * 取webcontext里面文件的相对路径 其余的都当前端页面处理
     *
     *  增加了对内部类的处理
     * @param classPath
     * @return
     */
    public Map initFile(List classPath) {
        //获取文件
        String root = generateProjectFile((String) classPath.get(0));
        Map result = new HashMap();
        for (int i = 0; i < classPath.size(); i++) {
            String path = (String) classPath.get(i);
            check(path);            //检查该路径是否在该项目中
            String[] ralationPath ;
            if (isInclude(path)) {
                ralationPath =generateClassesPath(path);
            }
            else {
                ralationPath = generateHTMLPath(path);
            }

            createFiles(root ,ralationPath);
            result.put(path, ralationPath);
        }
        return result;
    }




    /**
     * 检查该文件是否合法
     *
     * @param filePath
     * @return
     */
    private boolean check(String filePath) {
        boolean flag = false;
        if (filePath.contains(getProjectName(""))) {
            flag = true;
        }
        else {
            flag = false;
            logger.error(filePath + " is illegal");

        }
        return flag;

    }

    public boolean createFiles(String root ,String... path) {
        for(String p :path){
            createFile(root + p);
        }
        return true;
    }


    /**
     * 创建文件
     *
     * @param path
     * @return
     */
    public boolean createFile(String path) {
        boolean result = false;
        File file = new File(path);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            try {
                result = file.createNewFile();
            }
            catch (IOException e) {
                logger.error(path + "  create fail");
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 将class文件夹下面的文件截取路径
     *
     * @param path
     * @return
     */
    public String[] generateClassesPath(String path) {

        String[] s = path.split("\\\\com\\\\");
        return new String[]{File.separator + "WEB-INF" + File.separator + "classes" + File.separator + "com" + File.separator + s[1]};
    }

    /**
     * 获取该类的内部类，现在是在编译后的该类的目录下面通过正则找文件，
     * 时间复杂度  n*m
     * (很坑爹，就是每个class文件都需要遍历这个class目录，感觉需要优化)
     *  可以将当前文件目录下面的class缓存，然后排序，然后直接找下一个，看是不是  时间复杂度，主要是排序 n* log n
     * @param path
     * @return
     */
    public String[] getInnerClass(String path){
        return null;
    }


    /**
     * 将webcontext文件夹下面的文件截取路径
     *
     * @param path
     * @return
     */
    public String[] generateHTMLPath(String path) {
        String[] ss = path.split("\\\\" + projectName + "\\\\[a-zA-Z]+\\\\");
        return new String[]{File.separator + ss[1]};
    }


    /**
     * 检查该文件是否是class文件夹里面
     *
     * @param path
     * @return
     */
    public boolean isInclude(String path) {
        if (path.contains("\\com\\")||path.contains("\\org\\")||path.contains("\\common\\")) {
            for (int i = 0; i < SRC_INCLUDE.length; i++) {
                if (path.endsWith(SRC_INCLUDE[i])) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 获取项目名称，这里根据正则，取的是第二个分组，一般第一个分组为匹配的完整串
     *
     * @return
     */
    public String getProjectName(String physicalPath) {
        if (projectName == null) {
            String reg = "^D:\\\\ideaproject1\\\\([^\\\\]+)\\\\.+";
            Pattern p = Pattern.compile(reg);
            Matcher m = p.matcher(physicalPath);
            if (m.find()) {
                projectName = m.group(1);
            }
        }
        return projectName;
    }

    /**
     * 根据文件物理路径生成项目的物理路径
     *
     * @return
     */
    public String generateProjectFile(String classPath) {
        String filePath = OUTPUT_ROOTDIR + File.separator + getProjectName(classPath) + SUFFIX;
        File file = new File(filePath);
        try {
            if (!file.exists()) {
                if (file.mkdir()) {
                    return filePath;
                }

            }
        }
        catch (Exception e) {
            logger.error("create filecharset fail,the filecharset is " + filePath);
            e.printStackTrace();
        }
        return filePath;
    }


    /**
     * 复制文件
     *
     * @param source
     * @param desc
     * @return
     */
    public boolean copyFile(String source, String desc) {

        boolean result = false;
        File sourceFile = new File(source);
        File descFile = new File(desc);
        OutputStream out = null;
        InputStream in = null;
        try {
            byte[] b = new byte[1024];
            in = new FileInputStream(sourceFile);
            out = new FileOutputStream(OUTPUT_ROOTDIR+File.separator+projectName+SUFFIX+File.separator+descFile);
            int temp = 0;
            while ((temp = in.read(b)) != -1) {
                out.write(b, 0, temp);
            }
            out.flush();
            result = true;
            logger.info(source + " is copy to " + desc + " finish");
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                out.close();
                in.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) {


/**
 * 文件测试
 */
//        String[] path = {"D:\\ideaproject1\\jituanmonitor\\out\\production\\jituanmonitor\\com\\ct10000\\jituan\\monitor\\business\\job\\DownloadFromFtpUtil.class",
//                "D:\\ideaproject1\\jituanmonitor\\out\\production\\jituanmonitor\\com\\ct10000\\jituan\\monitor\\business\\job\\DownloadMbyhJob.class",
//                "D:\\ideaproject1\\jituanmonitor\\out\\production\\jituanmonitor\\com\\ct10000\\jituan\\monitor\\business\\task\\JobStart.class"};

        /**
         * 流管 文件上传
         */
//        String[] path = {
//        "D:\\ideaproject1\\jituanmonitor\\out\\production\\jituanmonitor\\com\\ct10000\\jituan\\monitor\\business\\job\\DownloadMbyhJob.class",
//        "D:\\ideaproject1\\jituanmonitor\\out\\production\\jituanmonitor\\com\\ct10000\\jituan\\monitor\\business\\util\\FtpUtil.class",
////        "D:\\ideaproject1\\jituanmonitor\\out\\production\\jituanmonitor\\com\\ct10000\\jituan\\monitor\\business\\task\\JobStart.class",
//        "D:\\ideaproject1\\jituanmonitor\\out\\production\\jituanmonitor\\com\\ct10000\\jituan\\monitor\\business\\util\\FileManager.class",
//        "D:\\ideaproject1\\jituanmonitor\\out\\production\\jituanmonitor\\com\\ct10000\\jituan\\monitor\\business\\job\\DownloadFromFtpUtil.class"
//        };


        /**
         * 实名登记
         */
//        String[] path = {"D:\\ideaproject1\\wap3.0\\out\\production\\wap3.0\\com\\ct10000\\page\\wap\\Logignin.class",
//                "D:\\ideaproject1\\wap3.0\\out\\production\\wap3.0\\com\\ct10000\\page\\market\\Threeupfournew.class",
//                "D:\\ideaproject1\\wap3.0\\webcontext\\wap\\loginin\\css\\login.css",
//                "D:\\ideaproject1\\wap3.0\\webcontext\\wap\\loginin\\images\\icon-lock.png",
//                "D:\\ideaproject1\\wap3.0\\webcontext\\wap\\loginin\\images\\icon-user.png",
//                "D:\\ideaproject1\\wap3.0\\webcontext\\wap\\loginin\\images\\right.jpg",
//                "D:\\ideaproject1\\wap3.0\\webcontext\\wap\\loginin\\js\\login.js",
//                "D:\\ideaproject1\\wap3.0\\webcontext\\wap\\loginin\\index.whtml",
//                "D:\\ideaproject1\\wap3.0\\webcontext\\wap\\loginin\\indexsmdj.whtml"};

        /**
         * smdj 修改
         */
//        String[] path = {
//                "D:\\ideaproject1\\bizdis_esb\\out\\production\\bizdis_esb\\com\\ct10000\\bizdis\\app\\QueryPhoneWhiteListService.class",
//                "D:\\ideaproject1\\bizdis_esb\\src\\com\\ct10000\\bizdis\\activity\\domain\\Wt_wap_phone_whitelistDomain_exp.xml"
//                };


        /**
         * 充值
         */
//        String[] path = {
//                "D:\\ideaproject1\\wt_pay\\out\\production\\wt_pay\\com\\ct10000\\page\\PayUtil.class",
//                "D:\\ideaproject1\\wt_pay\\out\\production\\wt_pay\\com\\ct10000\\page\\RechargeAction.class",
//                "D:\\ideaproject1\\wt_pay\\out\\production\\wt_pay\\com\\ct10000\\page\\TyPayService.class",
//                "D:\\ideaproject1\\wt_pay\\out\\production\\wt_pay\\com\\ct10000\\page\\util\\HTTPTools.class",
//                "D:\\ideaproject1\\wt_pay\\out\\production\\wt_pay\\com\\ct10000\\page\\util\\RequestParameterUtils.class",
//                "D:\\ideaproject1\\wt_pay\\out\\production\\wt_pay\\com\\ct10000\\page\\util\\ResponseCode.class",
//                "D:\\ideaproject1\\wt_pay\\out\\production\\wt_pay\\com\\ct10000\\service\\RechargeService.class"
//        };


        /**
         * 互联网卡
         */
//        String[] path = {
//                "D:\\ideaproject1\\wt_order_gather\\out\\production\\wt_order_gather\\com\\ct10000\\util\\RequestDataUtil.class",
//                "D:\\ideaproject1\\wt_order_gather\\out\\production\\wt_order_gather\\com\\ct10000\\page\\order\\Ic.class",
//                "D:\\ideaproject1\\wt_order_gather\\out\\production\\wt_order_gather\\com\\ct10000\\util\\HTTPUtils.class",
//                "D:\\ideaproject1\\wt_order_gather\\out\\production\\wt_order_gather\\com\\ct10000\\util\\HTTPUtils$1.class",
//                "D:\\ideaproject1\\wt_order_gather\\out\\production\\wt_order_gather\\com\\ct10000\\util\\HTTPUtils$2.class",
//                "D:\\ideaproject1\\wt_order_gather\\out\\production\\wt_order_gather\\com\\ct10000\\util\\HTTPUtils$3.class",
////                "D:\\ideaproject1\\wt_order_gather\\out\\production\\wt_order_gather\\com\\ct10000\\util\\HTTPUtils$4.class",
//                "D:\\ideaproject1\\wt_order_gather\\out\\production\\wt_order_gather\\com\\ct10000\\cfg\\domain\\Wt_wap_paraconfigDomain.class",
//                "D:\\ideaproject1\\wt_order_gather\\web\\WEB-INF\\lib\\httpclient-4.5.3.jar",
//                "D:\\ideaproject1\\wt_order_gather\\web\\WEB-INF\\lib\\httpcore-4.4.6.jar",
//                "D:\\ideaproject1\\wt_order_gather\\web\\WEB-INF\\lib\\quartz-all-1.5.2.jar"
//        };


//        String[] path = {
//
//                "D:\\ideaproject1\\wt_order_gather\\out\\production\\wt_order_gather\\com\\ct10000\\page\\order\\ScOrderSync.class",
//                "D:\\ideaproject1\\wt_order_gather\\out\\production\\wt_order_gather\\com\\ct10000\\service\\area\\ScOrderSyncService.class",
//                "D:\\ideaproject1\\wt_order_gather\\src\\com\\ct10000\\cfg\\domain\\Wt_common_order_instanceDomain_exp.xml",
//                "D:\\ideaproject1\\wt_order_gather\\src\\com\\ct10000\\cfg\\domain\\Wt_common_order_processDomain_exp.xml"
//        };



//        String[] path = {"D:\\ideaproject1\\wap3.0\\out\\production\\wap3.0\\com\\ct10000\\page\\market\\OrderSync.class"};


        //wt11888充值接口埋点
        String[] path = {
        "D:\\ideaproject1\\esb2_dubbo\\out\\production\\esb2_dubbo\\com\\ct10000\\esb\\system\\domain\\Kfk_annotationDomain.class",
        "D:\\ideaproject1\\esb2_dubbo\\out\\production\\esb2_dubbo\\com\\ct10000\\esb\\system\\domain\\Kfk_binaryAnnotationDomain.class",
        "D:\\ideaproject1\\esb2_dubbo\\out\\production\\esb2_dubbo\\com\\ct10000\\esb\\system\\domain\\Kfk_endpointDomain.class",
        "D:\\ideaproject1\\esb2_dubbo\\out\\production\\esb2_dubbo\\com\\ct10000\\esb\\system\\domain\\Kfk_instanceDomain.class",
        "D:\\ideaproject1\\esb2_dubbo\\out\\production\\esb2_dubbo\\com\\ct10000\\esb\\system\\util\\KafkaUtils.class",
        "D:\\ideaproject1\\esb2_dubbo\\out\\production\\esb2_dubbo\\com\\ct10000\\esb\\system\\util\\TimeUtils.class",
        "D:\\ideaproject1\\esb2_dubbo\\out\\production\\esb2_dubbo\\com\\ct10000\\esb\\system\\constant\\ServerInfo.class",
        "D:\\ideaproject1\\esb2_dubbo\\out\\production\\esb2_dubbo\\com\\ct10000\\esb\\dubbo\\bean\\crm\\RechargeBean.class",
        "D:\\ideaproject1\\esb2_dubbo\\webcontext\\WEB-INF\\lib\\kafka-clients-0.8.2.2.jar"
        };



        Project project = new Project();
        Set set = new HashSet();
        set.addAll(Arrays.asList(path));

        Map map = project.initFile(Arrays.asList(set.toArray()));
        for (Object t : map.keySet()) {
            project.copyFile((String) t, ((String[]) map.get(t))[0]);
        }
        System.out.println("");


        /**
         * 正则表达式测试
         */
/*        String reg = "^D:\\\\ideaproject1\\\\([^\\\\]+)\\\\.+";
        String temp ="D:\\ideaproject1\\bdspeed\\out\\production\\bdspeed\\com\\ct10000\\wt\\esb";

        System.out.println(temp.matches(reg));
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(temp);
        int i = 0;
        int sum = m.groupCount();
        System.out.println(sum);
        while(m.find()){
            System.out.println("match number"+i);
            System.out.println(m.start());
            System.out.println(m.end());
            System.out.println(m.group());
            System.out.println(" "+i+ " " +m.group(1));
            System.out.println("######################");
        }*/


//        String path = "D:\\ideaproject1\\esb\\out\\production\\esb\\com\\ct10000\\esb\\param\\IValidate.class";
//        String[] s = path.split("\\\\com\\\\");
//        System.out.println(File.separator);
//        for (String t : s) {
//            System.out.println(t);
//        }
//
//        path = "D:\\ideaproject1\\esb\\webContext\\e3\\tree\\E3Tree.version.properties";
//        String[] ss = path.split("\\\\esb\\\\[a-zA-Z]+\\\\");
//        for (String t : ss) {
//            System.out.println(t);
//        }

    }


}